package top.lixunda.ecommerce.server.good.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import top.lixunda.common.utils.ObjectValidators;
import top.lixunda.common.utils.StringUtils;
import top.lixunda.ecommerce.server.business.BaseServiceImpl;
import top.lixunda.ecommerce.server.good.api.entity.db.QiNiuFileDO;
import top.lixunda.ecommerce.server.good.config.QiNiuConfig;
import top.lixunda.ecommerce.server.good.mapper.QiNiuFileMapper;
import top.lixunda.ecommerce.server.good.service.IQiNiuFileService;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 七牛云对象存储文件上传回调数据 服务实现类
 * </p>
 *
 * @author Xumda
 * @since 2020-01-19
 */
@Service
public class QiNiuFileServiceImpl extends
        BaseServiceImpl<QiNiuFileMapper, QiNiuFileDO> implements IQiNiuFileService {

    private final QiNiuConfig qiNiuConfig;

    @Autowired
    public QiNiuFileServiceImpl(QiNiuConfig qiNiuConfig) {
        this.qiNiuConfig = qiNiuConfig;
    }

    /**
     * 根据id下载文件
     *
     * @param id      id
     * @param request HttpServletRequest
     * @return ResponseEntity
     */
    @Override
    public ResponseEntity<byte[]> downloadAsFileById(Integer id, HttpServletRequest request) {
        if (ObjectValidators.isEmpty(id)) {
            throw getAppException("参数不能为空");
        }
        QiNiuFileDO qiNiuFileDO = this.getById(id);
        if (ObjectValidators.isEmpty(qiNiuFileDO)) {
            throw getAppException("数据不存在");
        }
        String url = qiNiuConfig.getBaseUrl() + qiNiuFileDO.getFileKey();
        return super.downloadFileByUrl(url, StringUtils.randomFileName(""), request);
    }

    /**
     * 根据id下载文件，不推荐使用，推荐直接从七牛云进行下载
     *
     * @param url     文件网络地址
     * @param request HttpServletRequest
     * @return ResponseEntity
     */
    @Override
    public ResponseEntity<byte[]> downloadAsFileByUrl(String url, HttpServletRequest request) {
        if (ObjectValidators.isEmpty(url)) {
            throw getAppException("url不能为空");
        }
        return super.downloadFileByUrl(url, StringUtils.randomFileName(""), request);
    }
}
